<template>
  <div class="login_container">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <el-form
          class="login_form"
          :model="loginForm"
          :rules="rules"
          ref="loginForms"
        >
          <el-form-item prop="username">
            <el-input
              :prefix-icon="User"
              placeholder="请输入账号"
              v-model="loginForm.username"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              type="password"
              :prefix-icon="Lock"
              placeholder="请输入密码"
              v-model="loginForm.password"
              show-password
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              class="login_btn"
              type="primary"
              @click="login"
              :loading="loading"
            >
              登录
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { User, Lock } from '@element-plus/icons-vue'
import useUserStore from '@/store/modules/user'
import { useRouter } from 'vue-router'
import { ElNotification } from 'element-plus'
import { getTime } from '@/utils/time'
import { ref } from 'vue'
const userStore = useUserStore()
const $router = useRouter()
let loginForm = ref({
  username: '',
  password: '',
})
let loginForms = ref()
// 表单校验
const rules = {
  username: [{ required: true, message: '用户名不能为空', tigger: 'blur' }],
  password: [
    { required: true, message: '密码不能为空', tigger: 'blur' },
    {
      required: true,
      min: 6,
      max: 12,
      message: '密码长为6-12位',
      tigger: 'change',
    },
  ],
}
// 设置登录按钮的加载效果
let loading = ref(false)
const login = async () => {
  // 表单校验完成再发请求
  await loginForms.value.validate()
  loading.value = true
  try {
    // 也可以使用.then
    await userStore.userLogin(loginForm.value)
    $router.push('/')
    ElNotification({
      type: 'success',
      message: '欢迎回来',
      title: `HI,${getTime()}`,
    })
    loading.value = false
  } catch (error) {
    ElNotification({
      type: 'error',
      message: (error as Error).message,
    })
    loading.value = false
  }
}
</script>

<style scoped lang="scss">
.login_container {
  width: 100%;
  height: 100vh;
  background: url('@/assets/images/background.jpg') no-repeat;
  background-size: cover;

  .login_form {
    position: relative;
    width: 80%;
    background: url('@/assets/images/login_form.png') no-repeat;
    background-size: cover;
    top: 35vh;
    padding: 40px;
    left: 10%;

    .login_btn {
      width: 100%;
    }
  }
}
</style>
